package com.yonyou.crm.bpub.detail.service;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.*;

import com.yonyou.crm.sys.user.service.UserBizServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.bpub.detail.entity.*;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.cum.customer.entity.*;
import com.yonyou.crm.cum.customer.service.*;
import com.yonyou.crm.sys.modules.entity.BiztypeEnum;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class CustomerDetails extends BaseDetails{

	@Autowired
	CustomerBizServiceImpl service;
	
	@Autowired
	CustomerSalesBizServiceImpl saleService;
	
	@Autowired
	CustomerFollowBizServiceImpl followService;

	@Autowired
	UserBizServiceImpl userService;
	
	private String[] itemkeyOfEnumList = {"level", "type", "state","industry", "cannelType", "source"};
	
	private String[] itemkeyOfPicList = {"taxCertificate", "bizLicense", "orgCertificate", "docFront", "docReverse"};
	
	@Override
	public <T extends Serializable> T getDetail(long id) {
		CustomerVO obj = service.getDetail(id);
		if ((obj != null) && (obj.getId() == null)) {
			obj = null;
		}
		return (T)obj;
	}
	
	/**
	 * 获取详情模板
	 */
	@Override
	public  <T extends Serializable> Map<String, List<DetailsGroupVO>> getLayout(T obj) {
		CustomerVO vo = (CustomerVO) obj;
		//Long biztypeId = vo.getBiztypeId();
		long biztypeId = BiztypeEnum.CUSTOMER_1.getValue();
		return layoutService.getMobileDetailTemplateForCurrentUser(biztypeId);
	}
	
	@Override
	public <T extends Serializable> List<DetailsGroupVO> getHeader(T obj, Map<String, List<DetailsGroupVO>> layoutList) throws CrmMessageException {
		
		List<DetailsGroupVO> headerlist = getLayout(layoutList, "header");
		
		CustomerVO vo = (CustomerVO) obj;
		
		Class<?> className = vo.getClass();
		
		if ((headerlist != null) && (headerlist.size() > 0)) {
			for(DetailsGroupVO header : headerlist) {
				List<DetailsItemVO> groupdata = header.getGroupdata();
				if ((groupdata != null) && (groupdata.size() > 0)) {
					for(DetailsItemVO dataItem : groupdata) {
						String itemkey = dataItem.getItemkey();
						if (!itemkey.equals("")) {
							Object data;
							Object datavalue = "";
							if (itemkey.equals("province_city_district")) {//对省市区处理
								datavalue = getAddressInfo(vo.getProvinceName(), vo.getCityName(), vo.getDistrictName(), "");
							} else if (itemkey.equals("ownerUserId")) {//对负责人处理
								//TODO目前只获取一个负责人信息
								//获取负责人信息
								List<CustomerSalesVO> saleList = vo.getSalesVOs();
								CustomerSalesVO sale = null;
								if (saleList != null) {
									sale = saleList.get(0);
								}
								datavalue = (sale == null) ? "" : sale.getOwnerUserName();
							} else {
								try {
									//首字母大写
									char[] cs = itemkey.toCharArray();
									cs[0] = Character.toUpperCase(cs[0]);
									String funcName = String.valueOf(cs);
									//获取方法名称
									Method getObject = className.getMethod("get"+funcName);
									
									if (Arrays.asList(itemkeyOfEnumList).contains(itemkey)) {
										Method getObjectName = className.getMethod("get"+funcName+"Name");
										data = getObjectName.invoke(vo);
										datavalue = (data == null) ? "" : data.toString();
									} else if (Arrays.asList(itemkeyOfPicList).contains(itemkey)) {
										data = getObject.invoke(vo);
										datavalue = getPicUrl(data);
									} else {
										data = getObject.invoke(vo);
										datavalue = (data == null) ? "" : data.toString();
									}
								} catch (Exception e) {
									throw new CrmBusinessException("动态调用客户方法错误！", e);
								}
							}
							dataItem.setValue(datavalue);
						}
					}
				}
			}
		}
		
		//客户头部信息(固定，不可配置)
		DetailsGroupVO firstHeader = getFirstElementForHeaderList(vo);
		headerlist.add(0, firstHeader);
		return headerlist;
	}
	
	private DetailsGroupVO getFirstElementForHeaderList(CustomerVO vo) throws CrmMessageException{
		//客户头部信息(固定，不可配置)
		DetailsGroupVO header = new DetailsGroupVO();
		List<DetailsItemVO> headerData = new ArrayList<>();
		DetailsItemVO item;
		
		item = new DetailsItemVO();
		item.setItemkey("subbnstype");
		item.setName("业务类型");
		item.setValue(vo.getBiztypeId());
		item.setType("singlelinetext");
		headerData.add(item);
		
		item = new DetailsItemVO();
		item.setItemkey("name");
		item.setName("客户名称");
		item.setValue(vo.getName());
		item.setType("singlelinetext");
		headerData.add(item);
		
		item = new DetailsItemVO();
		item.setItemkey("type");
		item.setName("客户类型");
		item.setValue(vo.getTypeName());
		item.setType("flag");
		headerData.add(item);
		
		item = new DetailsItemVO();
		item.setItemkey("level");
		item.setName("客户等级");
		item.setValue(vo.getLevelName());
		item.setType("flag");
		headerData.add(item);
		
		item = new DetailsItemVO();
		item.setItemkey("state");
		item.setName("客户状态");
		item.setValue(vo.getStateName());
		item.setType("flag");
		headerData.add(item);

		item = new DetailsItemVO();
		item.setItemkey("cannelType");
		item.setName("渠道类型");
		item.setValue(vo.getCannelTypeName());
		item.setType("flag");
		headerData.add(item);
		
		//TODO目前只获取一个负责人信息
		//获取负责人信息
		List<CustomerSalesVO> saleList = vo.getSalesVOs();
		CustomerSalesVO sale = null;
		if (saleList != null) {
			sale = saleList.get(0);
		}
		
		item = new DetailsItemVO();
		item.setItemkey("ownerUserName");
		item.setName("负责人");
		item.setValue((sale == null || sale.getOwnerUserName() == null) ? "" : sale.getOwnerUserName());
		item.setType("singlelinetext");
		headerData.add(item);
		
		item = new DetailsItemVO();
		item.setItemkey("ownerUserId");
		item.setName("负责人Id");
		item.setValue((sale == null || sale.getOwnerUserId() == null) ? "" : String.valueOf(sale.getOwnerUserId()));
		item.setType("singlelinetext");
		headerData.add(item);
		
		item = new DetailsItemVO();
		item.setItemkey("ownerUserFilterList");
		item.setName("负责人筛选条件");
		List<DetailsFilterVO> filterList = new ArrayList<>();
		DetailsFilterVO filterItem;
		filterItem= new DetailsFilterVO("__Login__.orgId");
		filterList.add(filterItem);
		filterItem = new DetailsFilterVO("__Login__.deptId");
		filterList.add(filterItem);
		item.setValue(filterList);
		item.setType("singlelinetext");
		headerData.add(item);

		item = new DetailsItemVO();
		item.setItemkey("address");
		item.setName("地址");
		String address = getAddressInfo(vo.getProvinceName(), vo.getCityName(), vo.getDistrictName(), vo.getStreet());
		item.setValue(address);
		item.setType("address");
		//设置扩展项(地址经纬度)
		List<DetailsParamItemVO> paramList = new ArrayList<>();
		DetailsParamItemVO paramItem;
		paramItem = new DetailsParamItemVO("longitude", (vo.getLongitude() == null) ? "" : vo.getLongitude());
		paramList.add(paramItem);
		paramItem = new DetailsParamItemVO("latitude", (vo.getLatitude() == null) ? "" : vo.getLatitude());
		paramList.add(paramItem);
		item.setParamlist(paramList);
		headerData.add(item);
		
		item = new DetailsItemVO();
		item.setItemkey("followTime");
		item.setName("最近跟进");
		String followTime = (sale == null) ? "" : formateDate(sale.getFollowTime(), "yyyy-MM-dd");
		item.setValue(followTime);
		item.setType("singlelinetext");
		headerData.add(item);
		
		item = new DetailsItemVO();
		item.setItemkey("firstFollowTime");
		item.setName("首次跟进");
		String firstFollowTime = (sale == null) ? "" : formateDate(sale.getFirstFollowTime(), "yyyy-MM-dd");
		item.setValue(firstFollowTime);
		item.setType("singlelinetext");
		headerData.add(item);
		
		item = new DetailsItemVO();
		item.setItemkey("phone");
		item.setName("联系电话");
		List<String> phoneList = new ArrayList<>();
		String phone = (vo.getMobile() == null) ? "" : vo.getMobile();
		phoneList.add(phone);
		phone = (vo.getTel() == null) ? "" : vo.getTel();
		phoneList.add(phone);
		item.setValue(phoneList);
		item.setType("phone");
		headerData.add(item);

		header.setGroupdata(headerData);
		return header;
	}
	
	@Override
	public <T extends Serializable> List<DetailsGroupVO> getBody(T obj, Map<String, List<DetailsGroupVO>> layoutList){
		List<DetailsGroupVO> body = new ArrayList<DetailsGroupVO>();
		return body;
	}
	
	@Override
	public <T extends Serializable> List<DetailsFlagVO> getFlag(T obj){
		List<DetailsFlagVO> flags = new ArrayList<>();
		CustomerVO vo = (CustomerVO) obj;
		
		DetailsFlagVO flag = new DetailsFlagVO();
		String flagValue = "N";
		flag.setDes("identify");
		if (vo.getIsIdentified() == 1) {
			flagValue = "Y";
		}
		flag.setValue(flagValue);
		flags.add(flag);
		
		flag = new DetailsFlagVO();
		flagValue = "N";
		flag.setDes("follow");
		int followFlag = followService.isFollow(vo.getId());
		if (followFlag == 1) {
			flagValue = "Y";
		}
		flag.setValue(flagValue);
		flags.add(flag);
		
		return flags;
	}
	
	@Override
	public <T extends Serializable> List<String> getAction(T obj){
		List<String> actions = new ArrayList<>();
		CustomerVO vo = (CustomerVO) obj;
		Long userId = new Long(InvocationInfoProxy.getParameter("id"));
		//获取客户销售信息
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cumId", vo.getId());
		param.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		param.put("orgId", new Long(InvocationInfoProxy.getParameter("orgid")));
		List<CustomerSalesVO> saleList = saleService.selectByCustomer(param);
		
		if (saleList != null) {
			boolean isOnwer = false;
			boolean isManager = false;
			for(int i = 0; i < saleList.size(); i++) {
				CustomerSalesVO saleInfo = saleList.get(i);
				if (userId.toString().equals(saleInfo.getOwnerUserId().toString())) {
					isOnwer = true;
				}
				Long deptId = saleInfo.getOwnerDeptId();
				List<String> managerIdList = userService.getSMIdListByDeptId(deptId);
				if(managerIdList != null && managerIdList.contains(userId.toString())) {
					isManager = true;
				}
			}
			if (isManager) {
				actions.add("edit");
				actions.add("changeOwner");
				if (vo.getIsGroup() == CumGroupTypeEnum.COMPANY.getValue()) {
					actions.add("upgrade");
				}
			} else if (isOnwer) {
				actions.add("edit");
				if (vo.getIsGroup() == CumGroupTypeEnum.COMPANY.getValue()) {
					actions.add("upgrade");
				}
			}
		}
		return actions;
	}
	
}
